<script setup lang="ts">
const props = defineProps<{
  carFrontPhotoUrl: string,
  role: string
}>()
const fileList: Ref<any[]> = ref([])
const file = ref<any>(undefined)
const onOversize = (file: any) => {
  showToast('文件大小不能超过 3MB');
};
const afterRead = (tmp: any) => {
  if (tmp.file.size / 1024 / 1024 > 1) {
    showToast({
      message: '您上传的图片大小大于1MB，为了您的体验，推荐您上传小于1MB的图片，但您仍可继续~',
      duration: 3000
    })
  }
  file.value = tmp
}
let config = useRuntimeConfig()

function replaceURL(url: string): string {
  if (url === config.public.defaultUserAvatarURL) return url
  return config.public.enableReplaceImgURL ? url.replace(config.public.oldImgHost, config.public.newImgHost) : url
}

watch(
    () => {
      return props.carFrontPhotoUrl
    },
    () => {
      if (props.carFrontPhotoUrl)
        fileList.value.push({url: replaceURL(props.carFrontPhotoUrl), imageFit: 'contain'})
    }
    )

async function uploadFile() {
  if (!file.value) {
    showToast('请选择要上传的图片');
    return;
  }
  const formData = new FormData();
  formData.append('file', file.value.file)
  let newFrontUrl: string = ''
  await cFetch<any>(`/storage/api/upload?SESSION_TOKEN_KEY=${userStore().getToken()}`, {
    defaultOpts: {
      method: 'POST',
      body: formData
    }
  }).then((res) => {
    if (res.code === 200) {
      // showToast('上传成功')
      newFrontUrl = res.data[0].url
    }
  })
  await cFetch('/account/api/modifyVehicle', {
    auth: true,
    defaultOpts: {
      method: 'POST',
      body: {
        carFrontPhoto: newFrontUrl,
      }
    }
  }).then((res) => {
    if (res.code === 200) {
      showToast('修改车前照片成功')
    }
  })
}

</script>

<template>
  <div class="card">
    <h3 style="margin:0 0 5px">车辆正面（包含车牌）</h3>
    <van-uploader
        v-model="fileList"
        :max-size="3 * 1024 * 1024"
        @oversize="onOversize"
        reupload
        max-count="1"
        capture="camera"
        preview-size="12rem"
        :after-read="afterRead"
        image-fit="contain"
    />
    <van-button type="primary" @click="uploadFile" v-if="role==='0'">确认修改</van-button>
    <span v-else style="font-weight: bold;color: #299a29">已认证</span>
  </div>

</template>

<style scoped>
.card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
  width: 85%;
  border-radius: 10px;
  margin: 1rem auto;
  padding: 1rem;
}
</style>